package test5;

import java.math.BigDecimal;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RecursiveTask;

public class MultiForkJoinTool extends RecursiveTask {

    private Long start;
    private Long end;
    private BigDecimal result = new BigDecimal(1);

    public MultiForkJoinTool(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Object compute() {
        if (end - start <= 10) {
            for (Long i = start; i <= end; i++) {
                result = result.multiply(new BigDecimal(i));
            }
        }else {
            Long leftStart = start;
            Long leftEnd = (start + end) / 2;
            Long rightStart = (start + end) / 2 + 1;
            Long rightEnd = end;

            MultiForkJoinTool rightTask = new MultiForkJoinTool(leftStart, leftEnd);
            MultiForkJoinTool leftTask = new MultiForkJoinTool(rightStart, rightEnd);

            ForkJoinTask<BigDecimal> rightFork = rightTask.fork();
            ForkJoinTask<BigDecimal> leftFork = leftTask.fork();

            BigDecimal rightJoin = rightFork.join();
            BigDecimal leftJoin = leftFork.join();

            result=rightJoin.multiply(leftJoin);
        }
        return result;
    }
}
